package svc

import (
	"github.com/go-redis/redis/v8"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
	"mall/services/distributed-id/rpc/internal/config"
	"mall/services/distributed-id/rpc/internal/initialize/mysql"
	redis2 "mall/services/distributed-id/rpc/internal/initialize/redis"
	"mall/services/distributed-id/rpc/internal/mapper"
	"mall/services/distributed-id/rpc/internal/service/impl"
)

type ServiceContext struct {
	Config         config.Config
	DBEngin        *gorm.DB
	RedisClient    *redis.Client
	SegmentUseCase *impl.SegmentUseCase
}

func NewServiceContext(c config.Config) *ServiceContext {
	s := &ServiceContext{Config: c}
	// init mysql
	db, err := mysql.InitMysqlDB(c.MysqlConf)
	s.DBEngin = db
	if err != nil {
		return s
	}
	// init Redis ..
	initRedis, redisErr := redis2.InitRedis(c.RedisConf)
	if redisErr != nil {
		logx.Errorf("init redis error：%s", redisErr.Error())
		return s
	}
	s.RedisClient = initRedis
	useCase := impl.NewSegmentUseCase(db, initRedis, mapper.NewSegmentRepo())
	s.SegmentUseCase = useCase
	return s
}
